#include <string.h>
#include <stdlib.h>
#include <assert.h>

#include "String.h"
#include "Malloc.h"

char * strip ( char * line, char * pad ) {

  assert(line);
  assert(pad);

  // Handle characters at the beginning of the string
  char * iter = line;
  while ( *iter ) {
    char cur = *iter;
    if ( strchr( pad, cur ) ) {
      *iter = '\0';
      iter ++;
    }
    else {
      break;
    }
  }

  // Handle characters at the end
  char * last = iter + strlen(iter) - 1;
  while ( *last ) {
    char cur = *last;
    if ( strchr( pad, cur ) ) {
      *last = '\0';
      last --;
    }
    else {
      break;
    }
  }
 
  return iter;

}

int split( char * line, char ** buckets, char * delim ) {

  int idx = 0;
  buckets[0] = strtok( line, delim );
  while ( buckets[++idx] = strtok( NULL, delim ) ) {  }
  return idx;

}


char ** split_dynamic( char * line, char * delim ) {

  // Figure out how many tokens are in the string
  char * iter = line;
  int num = 0;
  while ( iter = strstr( iter, delim ) ) { 
    iter += strlen(delim);
    num ++;
  } 
  num ++;
  
  char ** toRet = Malloc( (num+1) * sizeof(char *) );
  char * start = line;
  iter = line;
  num = 0;
  while ( iter = strstr( iter, delim ) ) {
    int len = (iter - start) / sizeof(char);
    toRet[num] = Malloc( (len + 1) * sizeof(char) );
    strncpy( toRet[num], start, len );
    toRet[num][len] = '\0';
    iter += strlen(delim);
    start = iter;
    num ++;
  }
  int len = strlen(start);
  toRet[num] = Malloc( (len + 1) * sizeof(char) );
  strncpy( toRet[num], start, len );
  toRet[num][len] = '\0';
  num ++;
  toRet[num] = NULL;

  return toRet;
  
}
